package com.bupt.service;

import com.bupt.bean.*;
import com.bupt.config.*;
import com.bupt.dao.*;
import com.bupt.vo.*;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class DeviceService {

    @Autowired
    private DeviceRepository deviceRepository;

    @Autowired
    private DeviceChannelRepository deviceChannelRepository;

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private DeviceTypeAttributeRepository deviceTypeAttributeRepository;

    @Autowired
    private DeviceTypeAttributeSubRepository deviceTypeAttributeSubRepository;

    @Autowired
    private DeviceAttributeSubRepository deviceAttributeSubRepository;

    @Autowired
    private DeviceChannelAttributeRepository deviceChannelAttributeRepository;

    @Autowired
    private DeviceAttributeRepository deviceAttributeRepository;
    @Autowired
    private MessageMgtRepository messageMgtRepository;

    @Autowired
    private PrimaryKeyService primaryKeyService;

    @Autowired
    private DeviceNetworkRepository deviceNetworkRepository;

    @Autowired
    private DeviceTypeRepository deviceTypeRepository;

    @Autowired
    private AttributeValueTypeRepository attributeValueTypeRepository;

    @Autowired
    private DeviceTypeAttributeCheckRepository deviceTypeAttributeCheckRepository;


    //添加设备
    public DeviceResult add(String deviceName, Integer deviceType, String longitude, String latitude) {

        //校验设备名称
        Device byDeviceName = deviceRepository.findByDeviceName(deviceName);
        DeviceType byDeviceType = deviceTypeRepository.findByDeviceTypeId(deviceType);
        if(byDeviceName==null){
        }else{
            return new DeviceResult(CommonCode.FAIL,new Device());
        }
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        Device device = new Device();
        Integer device_id = primaryKeyService.getPrimaryKey("DEVICE_ID");
        device.setDeviceId(device_id);
        device.setDeviceName(deviceName);
        device.setDeviceTypeId(deviceType);
        device.setLongitude(longitude);
        device.setLatitude(latitude);
        device.setChannelNum(byDeviceType.getChannelNum());
        device.setAreaId(2);
        device.setStatus(1);
        device.setBrokenStatus(1);
        device.setStatusTime(timestamp);
        device.setCreatTime(timestamp);

        //如果设备类型是1   查询出device_type_attribute_t 表里
        // device_type_id=1 attribute_big_type=1的录入device_attribute_t
        //表里
        // 添加8条设备通道号

//        if (deviceType == 1) {

            // device_type_id=1 attribute_big_type=1的录入device_attribute_t
            List<DeviceTypeAttribute> allByDeviceTypeIdAndAttributeBigTypeList = deviceTypeAttributeRepository.findAllByDeviceTypeIdAndAttributeBigType(byDeviceType.getDeviceTypeId(), 1);

            //循环录入13条
            for (int i = 0; i < allByDeviceTypeIdAndAttributeBigTypeList.size(); i++) {
                DeviceTypeAttribute deviceTypeAttribute = allByDeviceTypeIdAndAttributeBigTypeList.get(i);
                DeviceAttribute deviceAttribute = new DeviceAttribute();
                Integer device_attribute_id = primaryKeyService.getPrimaryKey("DEVICE_ATTRIBUTE_ID");
                deviceAttribute.setDeviceAttributeId(device_attribute_id);
                deviceAttribute.setDeviceId(device_id);
                deviceAttribute.setDeviceAttributeType(deviceTypeAttribute.getAttributeType());
                deviceAttribute.setDeviceAttributeNameEn(deviceTypeAttribute.getAttributeNameEn());
                deviceAttribute.setDeviceAttributeNameCn(deviceTypeAttribute.getAttributeNameCn());
                deviceAttribute.setDeviceAttributeValue("0");
                deviceAttribute.setDeviceAttributeUnit(deviceTypeAttribute.getAttributeUnit());
                deviceAttribute.setDeviceTypeAttributeId(deviceTypeAttribute.getDeviceTypeAttributeId());
                deviceAttribute.setCreateTime(timestamp);
                deviceAttributeRepository.save(deviceAttribute);
            }

            // device_type_id=1 attribute_big_type=2的录入device_channel_t 8条通道  每条通道都有6个属性
            // device_attribute_t
            List<DeviceTypeAttribute> allByDeviceTypeIdAndAttributeBigTypeList2 = deviceTypeAttributeRepository.findAllByDeviceTypeIdAndAttributeBigType(byDeviceType.getDeviceTypeId(), 2);

            //循环录入8条通道
            for (int i = 0; i < byDeviceType.getChannelNum(); i++) {
                DeviceChannel deviceChannel = new DeviceChannel();
                Integer device_channel_id = primaryKeyService.getPrimaryKey("DEVICE_CHANNEL_ID");
                deviceChannel.setDeviceChannelId(device_channel_id);
                deviceChannel.setDeviceId(device_id);
                deviceChannel.setChannelIndex(i + 1);
                deviceChannel.setChannelEnable(0);
                deviceChannel.setChannelLen(0f);
                deviceChannelRepository.save(deviceChannel);

                //每个通道都有6条属性记录
                for (int j = 0; j < allByDeviceTypeIdAndAttributeBigTypeList2.size(); j++) {
                    DeviceTypeAttribute deviceTypeAttribute = allByDeviceTypeIdAndAttributeBigTypeList2.get(j);
                    DeviceChannelAttribute deviceChannelAttribute = new DeviceChannelAttribute();
                    Integer device_attribute_id = primaryKeyService.getPrimaryKey("DEVICE_CHANNEL_ATTRIBUTE_ID");
                    deviceChannelAttribute.setChannelAttributeId(device_attribute_id);
                    deviceChannelAttribute.setDeviceChannelId(device_channel_id);
                    deviceChannelAttribute.setChannelAttributeType(deviceTypeAttribute.getAttributeType());
                    deviceChannelAttribute.setChannelAttributeNameEn(deviceTypeAttribute.getAttributeNameEn());
                    deviceChannelAttribute.setChannelAttributeNameCn(deviceTypeAttribute.getAttributeNameCn());
                    deviceChannelAttribute.setChannelAttributeValue("0");
                    deviceChannelAttribute.setChannelAttributeUnit(deviceTypeAttribute.getAttributeUnit());
                    deviceChannelAttribute.setDeviceTypeAttributeId(deviceTypeAttribute.getDeviceTypeAttributeId());
                    deviceChannelAttribute.setCreateTime(timestamp);
                    deviceChannelAttributeRepository.save(deviceChannelAttribute);

                }
                //增加设备类型属性的子属性
                List<DeviceTypeAttributeSub> allByDeviceTypeIdList = deviceTypeAttributeSubRepository.findAllByDeviceTypeId(byDeviceType.getDeviceTypeId());
                if(allByDeviceTypeIdList.size()>0) {
                    for (int x = 0; x < allByDeviceTypeIdList.size(); x++) {
                        DeviceTypeAttributeSub deviceTypeAttributeSub = allByDeviceTypeIdList.get(x);
                        DeviceAttributeSub deviceAttributeSub = new DeviceAttributeSub();
                        Integer device_attribute_sub_id = primaryKeyService.getPrimaryKey("DEVICE_ATTRIBUTE_SUB_ID");
                        deviceAttributeSub.setDeviceAttributeSubId(device_attribute_sub_id);
                        deviceAttributeSub.setDeviceId(device_id);
                        deviceAttributeSub.setDeviceAttributeType(deviceTypeAttributeSub.getAttributeType());
                        deviceAttributeSub.setDeviceAttributeNameCn(deviceTypeAttributeSub.getAttributeNameCn());
                        deviceAttributeSub.setDeviceAttributeNameEn(deviceTypeAttributeSub.getAttributeNameEn());
                        deviceAttributeSub.setDeviceAttributeValue("0");
                        deviceAttributeSub.setDeviceAttributeUnit(deviceTypeAttributeSub.getAttributeUnit());
                        deviceAttributeSub.setCreateTime(timestamp);
                        deviceAttributeSub.setDeviceTypeAttributeSubId(deviceTypeAttributeSub.getDeviceTypeAttributeSubId());
                        deviceAttributeSubRepository.save(deviceAttributeSub);
                    }
                }
            }
//        }

        deviceRepository.save(device);
        //添加设备网络信息
        DeviceNetwork deviceNetwork = new DeviceNetwork();
        Integer device_network_id = primaryKeyService.getPrimaryKey("DEVICE_NETWORK_ID");
        deviceNetwork.setDeviceNetworkId(device_network_id);
        deviceNetwork.setDeviceId(device_id);
        deviceNetwork.setCreatTime(timestamp);
        deviceNetwork.setDeviceIp("127.0.0.1");
        deviceNetwork.setDeviceMac("00-00-00-00-00-00");
        deviceNetwork.setDeviceMask("255.255.255.0");
        deviceNetwork.setDeviceGw("192.168.1.1");
        deviceNetwork.setDeviceSn(device_id.toString());
        deviceNetwork.setDevicePort("3000");
        deviceNetworkRepository.save(deviceNetwork);

        DeviceResult result = new DeviceResult(CommonCode.SUCCESS, device);
        return result;
    }

    //修改设备
    public DeviceResult editDeviceById(Integer deviceId, Device device) {
        //校验重复
        //校验设备名称
        Device byDeviceName = deviceRepository.findByDeviceName(device.getDeviceName());
        if(byDeviceName==null){
        }else{
            if(device.getDeviceName().equals(byDeviceName.getDeviceName())){

            }else{
                return new DeviceResult(CommonCode.FAIL,new Device());
            }
        }

        Device befordevice = deviceRepository.findByDeviceId(deviceId);
        if (device != null) {
            befordevice.setDeviceName(device.getDeviceName());
            //befordevice.setDeviceTypeId(device.getDeviceTypeId());
            befordevice.setLongitude(device.getLongitude());
            befordevice.setLatitude(device.getLatitude());
            befordevice.setStatusTime(new Timestamp(System.currentTimeMillis()));

        }

        Device save = deviceRepository.save(befordevice);
        if (save != null) {
            DeviceResult deviceResult = new DeviceResult(CommonCode.SUCCESS, befordevice);
            return deviceResult;
        }
        return new DeviceResult(CommonCode.FAIL, null);
    }


    //查询设备状态  未启动 正常  断纤
    public Map deviceStatus() {
        HashMap<Object, Object> map = new HashMap<>();
        ArrayList<DeviceStatusResult> list = new ArrayList<>();
        ArrayList<DeviceStatusDescResult> deviceStatuslist = new ArrayList<>();
        int unstart = 0;
        int broken = 0;
        int right = 0;
        int deviceTypeone=0;
        int deviceTypetwo=0;
        boolean brokenFlagone=true;
        boolean brokenFlagtwo=true;
        String deviceIdsone="";
        String deviceIdstwo="";
        long nowTime = System.currentTimeMillis();

        List<Device> all = deviceRepository.findAll();
        if (all.size() > 0) {
            for (int i = 0; i < all.size(); i++) {

                if(all.get(i).getDeviceTypeId()==1){
                    if(!deviceIdsone.equals("")){
                        deviceIdsone=deviceIdsone+","+all.get(i).getDeviceId();
                    }else{
                        deviceIdsone=all.get(i).getDeviceId().toString();
                    }
                    deviceTypeone++;
                    if(all.get(i).getBrokenStatus()==2){brokenFlagone=false;}
                }else if(all.get(i).getDeviceTypeId()==2){
                    if(!deviceIdstwo.equals("")){
                        deviceIdstwo=deviceIdstwo+","+all.get(i).getDeviceId();
                    }else{
                        deviceIdstwo=all.get(i).getDeviceId().toString();
                    }

                    deviceTypetwo++;
                    if(all.get(i).getBrokenStatus()==2){brokenFlagtwo=false;}
                }

                long time = all.get(i).getStatusTime().getTime();
                int status = all.get(i).getStatus();
                int brokenStatus = all.get(i).getBrokenStatus();
                //状态为1且和当前时间相减超过60s的为未启动
                if (status == 1) {
                    if ((nowTime - time) / 1000 > 600) {
                        unstart++;
                        continue;
                    }
                }
                //brokenStauts=2未断纤
                if (brokenStatus == 2) {
                    broken++;
                    continue;
                }
                //状态为1且和当前时间相减不超过60s的为正常
                if (status == 1) {
                    if ((nowTime - time) / 1000 < 600) {
                        right++;
                        continue;
                    }
                }

            }
        }
        //上半部分
        DeviceStatusResult deviceStatusResultUnstart = new DeviceStatusResult();
        deviceStatusResultUnstart.setValue(unstart);
        deviceStatusResultUnstart.setName("未启动");
        list.add(deviceStatusResultUnstart);
        DeviceStatusResult deviceStatusResultBroken = new DeviceStatusResult();
        deviceStatusResultBroken.setValue(broken);
        deviceStatusResultBroken.setName("断纤");
        list.add(deviceStatusResultBroken);
        DeviceStatusResult deviceStatusResultRight = new DeviceStatusResult();
        deviceStatusResultRight.setValue(right);
        deviceStatusResultRight.setName("正常");
        list.add(deviceStatusResultRight);
        map.put("pieChart",list);
        //新增下半部分
        //设备类型ID为1时 3个默认 2个查一下
        if(deviceTypeone!=0){
            DeviceStatusDescResult deviceStatusDescResult=new DeviceStatusDescResult();
            deviceStatusDescResult.setDeviceTypeId(1);
            deviceStatusDescResult.setDeviceNum(deviceTypeone);
            deviceStatusDescResult.setLaserStatus("");
            deviceStatusDescResult.setVoltage(0);
            deviceStatusDescResult.setCoveOpeningStatus("");
            if(!brokenFlagone){
                deviceStatusDescResult.setLinkStatus(2);
            }else{
                deviceStatusDescResult.setLinkStatus(1);
            }
            String unhandledSql="SELECT COUNT(1)AS COUNT FROM event_t WHERE device_id IN("+deviceIdsone+") AND  STATUS=1";
            Query nativeQuery = entityManager.createNativeQuery(unhandledSql);
            String unhandledCount = nativeQuery.getResultList().get(0).toString();
            if(unhandledCount.equals("0")){
                deviceStatusDescResult.setIntrusionStatus(0);
            }else{
                deviceStatusDescResult.setIntrusionStatus(1);
            }
            deviceStatuslist.add(deviceStatusDescResult);
        }
        //设备类型为2时
        if(deviceTypetwo!=0){
            DeviceStatusDescResult deviceStatusDescResult=new DeviceStatusDescResult();
            deviceStatusDescResult.setDeviceTypeId(2);
            deviceStatusDescResult.setDeviceNum(deviceTypetwo);
            //激光器状态
            String laserSql="SELECT COUNT(1)AS COUNT  FROM device_attribute_t WHERE device_id IN("+deviceIdstwo+") AND device_attribute_name_en='laser_status' AND device_attribute_value='close'";
            Query nativeQuerylaser = entityManager.createNativeQuery(laserSql);
            String laserCount = nativeQuerylaser.getResultList().get(0).toString();
            if(laserCount.equals("0")){
                deviceStatusDescResult.setLaserStatus("open");
            }else{
                deviceStatusDescResult.setLaserStatus("close");
            }
            //电源
            String voltageSql="SELECT COUNT(1)AS COUNT FROM device_attribute_t WHERE device_id IN("+deviceIdstwo+")                      AND device_attribute_name_en='voltage' \n" +
                    "AND(  CAST(device_attribute_value AS  DECIMAL(5,4))<4.7 OR  CAST(device_attribute_value AS  DECIMAL(5,4))>5.2)";
            Query nativeQueryvoltage = entityManager.createNativeQuery(voltageSql);
            String voltageCount = nativeQueryvoltage.getResultList().get(0).toString();
            if(voltageCount.equals("0")){
                deviceStatusDescResult.setVoltage(0);
            }else{
                deviceStatusDescResult.setVoltage(1);
            }
            //机盖状态
            String coverOpenSql="SELECT COUNT(1)AS COUNT  FROM device_attribute_t WHERE device_id IN("+deviceIdstwo+")                       AND device_attribute_name_en='cover_opening_status' \n" +
                    " AND device_attribute_value='open'";
            Query nativeQuerycoverOpen = entityManager.createNativeQuery(coverOpenSql);
            String coverOpenCount = nativeQuerycoverOpen.getResultList().get(0).toString();
            if(coverOpenCount.equals("0")){
                deviceStatusDescResult.setCoveOpeningStatus("close");
            }else{
                deviceStatusDescResult.setCoveOpeningStatus("open");
            }

            //链路状态
            if(!brokenFlagtwo){
                deviceStatusDescResult.setLinkStatus(2);
            }else{
                deviceStatusDescResult.setLinkStatus(1);
            }
            //入侵状态
            String unhandledSql="SELECT COUNT(1)AS COUNT FROM event_t WHERE device_id IN("+deviceIdstwo+") AND  STATUS=1";
            Query nativeQuery = entityManager.createNativeQuery(unhandledSql);
            String unhandledCount = nativeQuery.getResultList().get(0).toString();
            if(unhandledCount.equals("0")){
                deviceStatusDescResult.setIntrusionStatus(0);
            }else{
                deviceStatusDescResult.setIntrusionStatus(1);
            }
            deviceStatuslist.add(deviceStatusDescResult);
        }
        map.put("deviceStatus",deviceStatuslist);
        return map;

    }

    //删除设备
    public Result deleteById(Integer deviceId) {
        Result result = new Result();
        Device device = deviceRepository.findByDeviceId(deviceId);
        if(device!=null){

            List<DeviceChannel>deviceChannelList=deviceChannelRepository.findAllByDeviceId(deviceId);
            //循环删除通道下的6条属性 然后删除通道
            for (int i = 0; i <deviceChannelList.size() ; i++) {
                DeviceChannel deviceChannel = deviceChannelList.get(i);
                    //删除设备通道属性
                    deviceChannelAttributeRepository.deleteByDeviceChannelId(deviceChannel.getDeviceChannelId());

                //删除设备通道
                deviceChannelRepository.deleteByDeviceChannelId(deviceChannel.getDeviceChannelId());
            }
            //删除设备子属性
            deviceAttributeSubRepository.deleteByDeviceId(deviceId);
            //删除设备属性
            deviceAttributeRepository.deleteByDeviceId(deviceId);

        //删除设备网络信息数据
        deviceNetworkRepository.deleteByDeviceId(deviceId);

        //删除设备
        deviceRepository.deleteByDeviceId(deviceId);


            result.setResult("删除成功");
            result.setCode(200);
            return result;
        }
           result.setResult("删除失败");
           result.setCode(404);
           return result;
    }

    //通过设备ID查询基本属性和光源属性
    public Map<String, Object> deviceAttributeById(Integer deviceId) {
        HashMap<String, Object> map = new HashMap<>();

        //查询TYPE是1的基本属性
        String sql = "SELECT da.device_attribute_id,da.device_attribute_name_cn,da.device_attribute_value,da.device_attribute_unit,dta.enable_config,da.Switch FROM device_t d,device_attribute_t da,device_type_attribute_t dta \n" +
                "                   WHERE d.device_id=da.device_id AND d.device_id="+deviceId+" AND dta.device_type_attribute_id=da.device_type_attribute_id AND da.device_attribute_type=1";
        Query query = entityManager.createNativeQuery(sql);
        List<DeviceAttributeVo> deviceAttributeVoBasicList = query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        //查询TYPE是2的光源属性
        String sql1 = "SELECT da.device_attribute_id,da.device_attribute_name_cn,da.device_attribute_value,da.device_attribute_unit,dta.enable_config,da.Switch FROM device_t d,device_attribute_t da,device_type_attribute_t dta \n" +
                "                   WHERE d.device_id=da.device_id AND d.device_id="+deviceId+" AND dta.device_type_attribute_id=da.device_type_attribute_id AND da.device_attribute_type=2";
        Query query1 = entityManager.createNativeQuery(sql1);
        List<DeviceAttributeVo> deviceAttributeVoLightSourceList = query1.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        //光源属于device_attribute_sub_t中device_attribute_sub_t.device_id=设备ID and device_attribute_sub_t.device_attribute_type=2 有数据时，状态为1，无数据时状态为0
        String sql2="SELECT device_attribute_name_cn,device_attribute_value,device_attribute_unit,DATE_FORMAT(create_time,'%Y-%m-%d %H:%i:%s')AS create_time FROM" +
                " device_attribute_sub_t  WHERE" +
                " device_attribute_type=2  AND device_id="+deviceId;
        Query query2 = entityManager.createNativeQuery(sql2);
        if(query2.getResultList().size()==0){
            map.put("status",0);
        }else{
            map.put("status",1);
            List<DeviceAttributeSubVo> deviceAttributeSubVoLightSourceList = query2.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
            map.put("lightSourceAttrDesc",deviceAttributeSubVoLightSourceList);
        }
        map.put("basicAttr",deviceAttributeVoBasicList);
        map.put("lightSourceAttr",deviceAttributeVoLightSourceList);

        return map;

    }


    //通道属性配置接口
    public Result deviceChannelAttributeUpdate(Integer channelAttributeId,String channelAttributeValue) {
        Result result = new Result();
        DeviceChannelAttribute channelAttribute = deviceChannelAttributeRepository.findByChannelAttributeId(channelAttributeId);
        if (channelAttribute != null) {
            channelAttribute.setChannelAttributeValue(channelAttributeValue);
            deviceChannelAttributeRepository.save(channelAttribute);
            if(channelAttribute.getChannelAttributeNameEn().equals("channellen")){
                DeviceChannel deviceChannel = deviceChannelRepository.findByDeviceChannelId(channelAttribute.getDeviceChannelId());
                if(deviceChannel!=null){
                    deviceChannel.setChannelLen(Float.valueOf(channelAttributeValue));
                    deviceChannelRepository.save(deviceChannel);
                    result.setResult("同时修改channellen，修改成功");
                    result.setCode(200);
                    return result;
                }
            }
            result.setResult("修改成功");
            result.setCode(200);
            return result;
        }
        result.setResult("此ID查询不到通道属性，修改失败");
        result.setCode(404);
        return result;

    }
    //设备类型ID=2时设备光源属性配置
    public Result deviceLightAttribute(Integer deviceTypeId,Integer deviceAttributeId,String deviceAttributeValue,Integer deviceAttributeSwitch) {
        Result result = new Result();
        if(deviceTypeId.intValue()!=2){
            result.setResult("设备类型ID不是2，修改失败");
            result.setCode(404);
            return result;
        }
        DeviceAttribute deviceAttribute = deviceAttributeRepository.findBydeviceAttributeId(deviceAttributeId);
        if (deviceAttribute != null) {
            deviceAttribute.setDeviceAttributeValue(deviceAttributeValue);
            deviceAttribute.setSwitch(deviceAttributeSwitch);
        }
        DeviceAttribute save = deviceAttributeRepository.save(deviceAttribute);
        if (save != null) {
            //deviceIp
            DeviceNetwork deviceNetwork = deviceNetworkRepository.findByDeviceId(save.getDeviceId());

            String deviceAttributeNameEn = save.getDeviceAttributeNameEn();
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            if(deviceAttributeNameEn.equals("unl_elec_curr")){
                if(deviceAttributeSwitch.intValue()==1){
                    MessageMgt mm=new MessageMgt();
                    Integer message_mgt_id = primaryKeyService.getPrimaryKey("MESSAGE_MGT_ID");
                    mm.setMessageMgtId(message_mgt_id);
                    mm.setDeviceId(save.getDeviceId());
                    mm.setDeviceIp(deviceNetwork.getDeviceIp());
                    mm.setState(0);
                    mm.setRepeatNum(0);
                    mm.setCreateTime(timestamp);
                    mm.setMsgBody(null);
                    mm.setMsgType(1);
                    messageMgtRepository.save(mm);
                    MessageMgt mmtwo=new MessageMgt();
                    Integer message_mgt_id_two = primaryKeyService.getPrimaryKey("MESSAGE_MGT_ID");
                    mmtwo.setMessageMgtId(message_mgt_id_two);
                    mmtwo.setDeviceId(save.getDeviceId());
                    mmtwo.setDeviceIp(deviceNetwork.getDeviceIp());
                    mmtwo.setState(0);
                    mmtwo.setRepeatNum(0);
                    mmtwo.setCreateTime(timestamp);
                    mmtwo.setMsgBody(deviceAttributeValue);
                    mmtwo.setMsgType(17);
                    messageMgtRepository.save(mmtwo);
                }else if(deviceAttributeSwitch.intValue()==0){
                    MessageMgt mmtwo=new MessageMgt();
                    Integer message_mgt_id_two = primaryKeyService.getPrimaryKey("MESSAGE_MGT_ID");
                    mmtwo.setMessageMgtId(message_mgt_id_two);
                    mmtwo.setDeviceId(save.getDeviceId());
                    mmtwo.setDeviceIp(deviceNetwork.getDeviceIp());
                    mmtwo.setState(0);
                    mmtwo.setRepeatNum(0);
                    mmtwo.setCreateTime(timestamp);
                    mmtwo.setMsgBody(deviceAttributeValue);
                    mmtwo.setMsgType(17);
                    messageMgtRepository.save(mmtwo);
                    MessageMgt mm=new MessageMgt();
                    Integer message_mgt_id = primaryKeyService.getPrimaryKey("MESSAGE_MGT_ID");
                    mm.setMessageMgtId(message_mgt_id);
                    mm.setDeviceId(save.getDeviceId());
                    mm.setDeviceIp(deviceNetwork.getDeviceIp());
                    mm.setState(0);
                    mm.setRepeatNum(0);
                    mm.setCreateTime(timestamp);
                    mm.setMsgBody(null);
                    mm.setMsgType(6);
                    messageMgtRepository.save(mm);
                }

                result.setResult("修改成功");
                result.setCode(200);
                return result;
            }else if(deviceAttributeNameEn.equals("rec_edfa_elec_curr")){
                if(deviceAttributeSwitch.intValue()==1){
                    MessageMgt mm=new MessageMgt();
                    Integer message_mgt_id = primaryKeyService.getPrimaryKey("MESSAGE_MGT_ID");
                    mm.setMessageMgtId(message_mgt_id);
                    mm.setDeviceId(save.getDeviceId());
                    mm.setDeviceIp(deviceNetwork.getDeviceIp());
                    mm.setState(0);
                    mm.setRepeatNum(0);
                    mm.setCreateTime(timestamp);
                    mm.setMsgBody(null);
                    mm.setMsgType(2);
                    messageMgtRepository.save(mm);
                    MessageMgt mmtwo=new MessageMgt();
                    Integer message_mgt_id_two = primaryKeyService.getPrimaryKey("MESSAGE_MGT_ID");
                    mmtwo.setMessageMgtId(message_mgt_id_two);
                    mmtwo.setDeviceId(save.getDeviceId());
                    mmtwo.setDeviceIp(deviceNetwork.getDeviceIp());
                    mmtwo.setState(0);
                    mmtwo.setRepeatNum(0);
                    mmtwo.setCreateTime(timestamp);
                    mmtwo.setMsgBody(deviceAttributeValue);
                    mmtwo.setMsgType(18);
                    messageMgtRepository.save(mmtwo);
                }else if(deviceAttributeSwitch.intValue()==0){
                    MessageMgt mmtwo=new MessageMgt();
                    Integer message_mgt_id_two = primaryKeyService.getPrimaryKey("MESSAGE_MGT_ID");
                    mmtwo.setMessageMgtId(message_mgt_id_two);
                    mmtwo.setDeviceId(save.getDeviceId());
                    mmtwo.setDeviceIp(deviceNetwork.getDeviceIp());
                    mmtwo.setState(0);
                    mmtwo.setRepeatNum(0);
                    mmtwo.setCreateTime(timestamp);
                    mmtwo.setMsgBody(deviceAttributeValue);
                    mmtwo.setMsgType(18);
                    messageMgtRepository.save(mmtwo);
                    MessageMgt mm=new MessageMgt();
                    Integer message_mgt_id = primaryKeyService.getPrimaryKey("MESSAGE_MGT_ID");
                    mm.setMessageMgtId(message_mgt_id);
                    mm.setDeviceId(save.getDeviceId());
                    mm.setDeviceIp(deviceNetwork.getDeviceIp());
                    mm.setState(0);
                    mm.setRepeatNum(0);
                    mm.setCreateTime(timestamp);
                    mm.setMsgBody(null);
                    mm.setMsgType(7);
                    messageMgtRepository.save(mm);
                }
                result.setResult("修改成功");
                result.setCode(200);
                return result;
            }else if(deviceAttributeNameEn.equals("pulse_edfa_elec_curr")){
                if(deviceAttributeSwitch.intValue()==1){
                    MessageMgt mm=new MessageMgt();
                    Integer message_mgt_id = primaryKeyService.getPrimaryKey("MESSAGE_MGT_ID");
                    mm.setMessageMgtId(message_mgt_id);
                    mm.setDeviceId(save.getDeviceId());
                    mm.setDeviceIp(deviceNetwork.getDeviceIp());
                    mm.setState(0);
                    mm.setRepeatNum(0);
                    mm.setCreateTime(timestamp);
                    mm.setMsgBody(null);
                    mm.setMsgType(3);
                    messageMgtRepository.save(mm);
                    MessageMgt mmtwo=new MessageMgt();
                    Integer message_mgt_id_two = primaryKeyService.getPrimaryKey("MESSAGE_MGT_ID");
                    mmtwo.setMessageMgtId(message_mgt_id_two);
                    mmtwo.setDeviceId(save.getDeviceId());
                    mmtwo.setDeviceIp(deviceNetwork.getDeviceIp());
                    mmtwo.setState(0);
                    mmtwo.setRepeatNum(0);
                    mmtwo.setCreateTime(timestamp);
                    mmtwo.setMsgBody(deviceAttributeValue);
                    mmtwo.setMsgType(19);
                    messageMgtRepository.save(mmtwo);
                }else if(deviceAttributeSwitch.intValue()==0){
                    MessageMgt mmtwo=new MessageMgt();
                    Integer message_mgt_id_two = primaryKeyService.getPrimaryKey("MESSAGE_MGT_ID");
                    mmtwo.setMessageMgtId(message_mgt_id_two);
                    mmtwo.setDeviceId(save.getDeviceId());
                    mmtwo.setDeviceIp(deviceNetwork.getDeviceIp());
                    mmtwo.setState(0);
                    mmtwo.setRepeatNum(0);
                    mmtwo.setCreateTime(timestamp);
                    mmtwo.setMsgBody(deviceAttributeValue);
                    mmtwo.setMsgType(19);
                    messageMgtRepository.save(mmtwo);
                    MessageMgt mm=new MessageMgt();
                    Integer message_mgt_id = primaryKeyService.getPrimaryKey("MESSAGE_MGT_ID");
                    mm.setMessageMgtId(message_mgt_id);
                    mm.setDeviceId(save.getDeviceId());
                    mm.setDeviceIp(deviceNetwork.getDeviceIp());
                    mm.setState(0);
                    mm.setRepeatNum(0);
                    mm.setCreateTime(timestamp);
                    mm.setMsgBody(null);
                    mm.setMsgType(8);
                    messageMgtRepository.save(mm);
                }
                result.setResult("修改成功");
                result.setCode(200);
                return result;
            }else if(deviceAttributeNameEn.equals("raman_elec_curr")){
                if(deviceAttributeSwitch.intValue()==1){
                    MessageMgt mm=new MessageMgt();
                    Integer message_mgt_id = primaryKeyService.getPrimaryKey("MESSAGE_MGT_ID");
                    mm.setMessageMgtId(message_mgt_id);
                    mm.setDeviceId(save.getDeviceId());
                    mm.setDeviceIp(deviceNetwork.getDeviceIp());
                    mm.setState(0);
                    mm.setRepeatNum(0);
                    mm.setCreateTime(timestamp);
                    mm.setMsgBody(null);
                    mm.setMsgType(4);
                    messageMgtRepository.save(mm);
                    MessageMgt mmtwo=new MessageMgt();
                    Integer message_mgt_id_two = primaryKeyService.getPrimaryKey("MESSAGE_MGT_ID");
                    mmtwo.setMessageMgtId(message_mgt_id_two);
                    mmtwo.setDeviceId(save.getDeviceId());
                    mmtwo.setDeviceIp(deviceNetwork.getDeviceIp());
                    mmtwo.setState(0);
                    mmtwo.setRepeatNum(0);
                    mmtwo.setCreateTime(timestamp);
                    mmtwo.setMsgBody(deviceAttributeValue);
                    mmtwo.setMsgType(20);
                    messageMgtRepository.save(mmtwo);
                }else if(deviceAttributeSwitch.intValue()==0){
                    MessageMgt mmtwo=new MessageMgt();
                    Integer message_mgt_id_two = primaryKeyService.getPrimaryKey("MESSAGE_MGT_ID");
                    mmtwo.setMessageMgtId(message_mgt_id_two);
                    mmtwo.setDeviceId(save.getDeviceId());
                    mmtwo.setDeviceIp(deviceNetwork.getDeviceIp());
                    mmtwo.setState(0);
                    mmtwo.setRepeatNum(0);
                    mmtwo.setCreateTime(timestamp);
                    mmtwo.setMsgBody(deviceAttributeValue);
                    mmtwo.setMsgType(20);
                    messageMgtRepository.save(mmtwo);
                    MessageMgt mm=new MessageMgt();
                    Integer message_mgt_id = primaryKeyService.getPrimaryKey("MESSAGE_MGT_ID");
                    mm.setMessageMgtId(message_mgt_id);
                    mm.setDeviceId(save.getDeviceId());
                    mm.setDeviceIp(deviceNetwork.getDeviceIp());
                    mm.setState(0);
                    mm.setRepeatNum(0);
                    mm.setCreateTime(timestamp);
                    mm.setMsgBody(null);
                    mm.setMsgType(9);
                    messageMgtRepository.save(mm);
                }
                result.setResult("修改成功");
                result.setCode(200);
                return result;
            }

        }



        result.setResult("删除失败");
        result.setCode(404);
        return result;
    }


    //通过设备ID查询设备下的通道信息
    public List<DeviceChannelVo> deviceChannelById(Integer deviceId) {
        String sql = "SELECT d.device_name,dc.device_channel_id,dc.channel_index,dc.channel_enable " +
                "FROM device_channel_t dc,device_t d WHERE d.device_id=dc.device_id AND  dc.device_id="+deviceId;
        Query query = entityManager.createNativeQuery(sql);
        List<DeviceChannelVo> deviceChannelVoList = query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();


        /*for (int i = 0; i < deviceChannelVoList.size(); i++) {
            DeviceChannelVo deviceChannelVo = deviceChannelVoList.get(i);

         *//*   if(deviceChannelVo.getChannelEnable()==1){
                deviceChannelVo.setChannelEnableBoolean(true);
            }else if(deviceChannelVo.getChannelEnable()==2){
                deviceChannelVo.setChannelEnableBoolean(false);

            }*//*
        }*/

        return deviceChannelVoList;
    }

    //通过通道ID查询通道下的属性
    public List<ChannelAttributeVo> channelAttributeById(Integer deviceChannelId) {
        String sql = "SELECT dca.channel_attribute_id,dca.channel_attribute_name_cn,\n" +
                "\t\tdca.channel_attribute_value,dca.channel_attribute_unit,dca.Switch,dta.enable_config\n" +
                "\t\t FROM device_channel_attribute_t dca,device_type_attribute_t dta WHERE  dta.device_type_attribute_id=dca.device_type_attribute_id\n" +
                "\t\tAND dca.device_channel_id="+deviceChannelId;
        Query query = entityManager.createNativeQuery(sql);
        List<ChannelAttributeVo> channelAttributeVoList = query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        return channelAttributeVoList;
    }

    //通过设备ID查询设备下的网络配置
    public Map deviceNetworkById(Integer deviceId) {
        String sql = "SELECT d.device_name,dn.* FROM device_t d,device_network_t dn WHERE d.device_id=dn.device_id AND d.device_id="+deviceId;
        Query query = entityManager.createNativeQuery(sql);
        List<Map> channelAttributeVoList = query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        return channelAttributeVoList.get(0);
    }

    //通过IP修改单个设备下的网络配置
    public DeviceNetworkResult editDeviceNetworkById(Integer deviceNetworkId, DeviceNetwork deviceNetwork) {
        DeviceNetwork beforDeviceNetwork = deviceNetworkRepository.findByDeviceNetworkId(deviceNetworkId);
        if (beforDeviceNetwork != null) {
            //IP 子网掩码  网管 设备端口
            beforDeviceNetwork.setDeviceIp(deviceNetwork.getDeviceIp());
            beforDeviceNetwork.setDeviceMask(deviceNetwork.getDeviceMask());
            beforDeviceNetwork.setDeviceGw(deviceNetwork.getDeviceGw());
            beforDeviceNetwork.setDevicePort(deviceNetwork.getDevicePort());

        }

        DeviceNetwork save = deviceNetworkRepository.save(beforDeviceNetwork);
        if (save != null) {
            DeviceNetworkResult deviceNetworkResult = new DeviceNetworkResult(CommonCode.SUCCESS, beforDeviceNetwork);
            return deviceNetworkResult;
        }
        return new DeviceNetworkResult(CommonCode.FAIL, null);
    }

    //添加设备类型
    public DeviceTypeResult addDeviceType(DeviceType deviceType) {
        //校验设备类型名称
        DeviceType byDeviceTypeName = deviceTypeRepository.findByDeviceTypeName(deviceType.getDeviceTypeName());
        if (byDeviceTypeName == null) {
        } else {
            return new DeviceTypeResult(CommonCode.FAIL, new DeviceType());
        }
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        DeviceType newDeviceType = new DeviceType();
        Integer device_type_id = primaryKeyService.getPrimaryKey("DEVICE_TYPE_ID");
        newDeviceType.setDeviceTypeId(device_type_id);
        newDeviceType.setChannelNum(deviceType.getChannelNum());
        newDeviceType.setDeviceTypeDesc(deviceType.getDeviceTypeDesc());
        newDeviceType.setDeviceTypeName(deviceType.getDeviceTypeName());

        deviceTypeRepository.save(newDeviceType);
        DeviceTypeResult result = new DeviceTypeResult(CommonCode.SUCCESS, newDeviceType);
        return result;

    }

    //通过ID修改设备类型
    public DeviceTypeResult editDeviceType(Integer deviceTypeId, DeviceType deviceType) {
        //校验设备类型名称
        DeviceType byDeviceTypeName = deviceTypeRepository.findByDeviceTypeName(deviceType.getDeviceTypeName());
        if (byDeviceTypeName == null) {
        } else {
            if(deviceTypeId!=byDeviceTypeName.getDeviceTypeId()){
                return new DeviceTypeResult(CommonCode.FAIL, new DeviceType());
            }
        }

        DeviceType befordeviceType = deviceTypeRepository.findByDeviceTypeId(deviceTypeId);
        if (befordeviceType != null) {
            befordeviceType.setDeviceTypeName(deviceType.getDeviceTypeName());
            befordeviceType.setDeviceTypeDesc(deviceType.getDeviceTypeDesc());
            befordeviceType.setChannelNum(deviceType.getChannelNum());

        }

        DeviceType save = deviceTypeRepository.save(befordeviceType);
        if (save != null) {
            DeviceTypeResult deviceTypeResult = new DeviceTypeResult(CommonCode.SUCCESS, befordeviceType);
            return deviceTypeResult;
        }
        return new DeviceTypeResult(CommonCode.FAIL, null);
    }

    //通过ID删除设备类型
    public Result deleteDeviceTypeById(Integer deviceTypeId) {
        Result result = new Result();
        List<Device> device = deviceRepository.findAllByDeviceTypeId(deviceTypeId);
        if(device.size()>0){
            result.setResult("删除失败,请先删除设备");
            return result;
        }
        DeviceType deviceType = deviceTypeRepository.findByDeviceTypeId(deviceTypeId);

        if(deviceType!=null){
            deviceTypeRepository.deleteByDeviceTypeId(deviceTypeId);
            result.setResult("删除成功");
            return result;
        }
        result.setResult("删除失败");
        return result;
    }

    //根据设备类型ID查询报警参数
    public List findDeviceTypeAttributeCheckList(Integer deviceTypeId) {

        String sql = "SELECT dtac.*,dt.device_type_name,avt.attribute_value_type_name FROM device_type_attribute_check_t dtac,device_type_t dt,attribute_value_type_t avt WHERE dt.device_type_id=dtac.device_type_id AND avt.attribute_value_type_id=dtac.attribute_value_type_id AND dt.device_type_id="+deviceTypeId;
        Query query = entityManager.createNativeQuery(sql);
        List<DeviceTypeAttributeCheckAllVo> deviceTypeAttributeCheckAllVoList = query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        return deviceTypeAttributeCheckAllVoList;
    }

    //属性值类型
    public List deviceTypeAttributeCheckToAttributeValueType() {
        List<AttributeValueType> all = attributeValueTypeRepository.findAll();
        return all;
    }

    //添加报警参数
    public DeviceTypeAttributeCheckResult addDeviceTypeAttributeCheck(Integer deviceTypeId, DeviceTypeAttributeCheck deviceTypeAttributeCheck) {



        Integer device_type_attribute_check_id = primaryKeyService.getPrimaryKey("DEVICE_TYPE_ATTRIBUTE_CHECK_ID");
        deviceTypeAttributeCheck.setDeviceTypeAttributeCheckId(device_type_attribute_check_id);

        deviceTypeAttributeCheckRepository.save(deviceTypeAttributeCheck);
        DeviceTypeAttributeCheckResult result = new DeviceTypeAttributeCheckResult(CommonCode.SUCCESS, deviceTypeAttributeCheck);
        return result;


    }

    //通过ID修改报警参数
    public DeviceTypeAttributeCheckResult editDeviceTypeAttributeCheck(Integer deviceTypeAttributeCheckId, DeviceTypeAttributeCheck deviceTypeAttributeCheck) {

        DeviceTypeAttributeCheck beforDeviceTypeAttributeCheck = deviceTypeAttributeCheckRepository.findByDeviceTypeAttributeCheckId(deviceTypeAttributeCheckId);

        if (beforDeviceTypeAttributeCheck != null) {
            beforDeviceTypeAttributeCheck.setAttributeNameEn(deviceTypeAttributeCheck.getAttributeNameEn());
            beforDeviceTypeAttributeCheck.setAttributeNameCn(deviceTypeAttributeCheck.getAttributeNameCn());
            beforDeviceTypeAttributeCheck.setAttributeValueTypeId(deviceTypeAttributeCheck.getAttributeValueTypeId());

        }

        DeviceTypeAttributeCheck save = deviceTypeAttributeCheckRepository.save(beforDeviceTypeAttributeCheck);
        if (save != null) {
            DeviceTypeAttributeCheckResult deviceTypeAttributeCheckResult = new DeviceTypeAttributeCheckResult(CommonCode.SUCCESS, beforDeviceTypeAttributeCheck);
            return deviceTypeAttributeCheckResult;
        }
        return new DeviceTypeAttributeCheckResult(CommonCode.FAIL, null);
    }

    //通过ID删除报警参数
    public Result deleteDeviceTypeAttributeCheckById(Integer deviceTypeAttributeCheckId) {
        Result result = new Result();
        DeviceTypeAttributeCheck deviceTypeAttributeCheck= deviceTypeAttributeCheckRepository.findByDeviceTypeAttributeCheckId(deviceTypeAttributeCheckId);
        if(deviceTypeAttributeCheck!=null){
            deviceTypeAttributeCheckRepository.deleteByDeviceTypeAttributeCheckId(deviceTypeAttributeCheckId);


            result.setResult("删除成功");
            return result;
        }
        result.setResult("删除失败");
        return result;
    }

    //属性类型
    public List<SysConst> attributeType() {
        String sql = "SELECT const_value,const_desc FROM sys_const_t WHERE const_group_name='ATTRIBUTE_TYPE'";
        Query query = entityManager.createNativeQuery(sql);
        List<SysConst> sysConstList = query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        return sysConstList;
    }

    //配置开关
    public List<SysConst> configStatus() {
        String sql = "SELECT const_value,const_desc FROM sys_const_t WHERE const_group_name='CONFIG_STATUS'";
        Query query = entityManager.createNativeQuery(sql);
        List<SysConst> sysConstList = query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        return sysConstList;
    }
    //设备开关
    public List<SysConst> enableDevice() {
        String sql = "SELECT const_value,const_desc FROM sys_const_t WHERE const_group_name='ENABLE'";
        Query query = entityManager.createNativeQuery(sql);
        List<SysConst> sysConstList = query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        return sysConstList;
    }

    //根据设备类型ID和大类查询设备属性或通道属性
    public List findDeviceTypeAttributeList(Integer deviceTypeId, Integer attributeBigType) {
        String sql = "SELECT ed.const_desc AS edconst_desc,ec.const_desc AS ecconst_desc,at.const_desc AS atconst_desc,dt.device_type_name,dta.* FROM device_type_attribute_t dta,device_type_t dt,\n" +
                "(SELECT const_value,const_desc FROM sys_const_t WHERE const_group_name='ATTRIBUTE_TYPE') AT,\n" +
                "(SELECT const_value,const_desc FROM sys_const_t WHERE const_group_name='CONFIG_STATUS')ec,\n" +
                "(SELECT const_value,const_desc FROM sys_const_t WHERE const_group_name='ENABLE')ed\n" +
                " WHERE dta.device_type_id=dt.device_type_id AND at.const_value=dta.attribute_type \n" +
                " AND ec.const_value=dta.enable_config  AND ed.const_value=dta.enable_device\n" +
                " AND dta.device_type_id= "+deviceTypeId+"  AND dta.attribute_big_type="+attributeBigType;
        Query query = entityManager.createNativeQuery(sql);
        List<DeviceTypeAttributeVo> deviceTypeAttributeVoList = query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        return deviceTypeAttributeVoList;
    }

    //通过ID删除设备属性或通道属性
    public Result deleteDeviceTypeAttributeById(Integer deviceTypeAttributeId,Integer attributeBigType) {
        Result result = new Result();

        DeviceTypeAttribute deviceTypeAttribute= deviceTypeAttributeRepository.findByDeviceTypeAttributeId(deviceTypeAttributeId);

        if(deviceTypeAttribute!=null){
            deviceTypeAttributeRepository.deleteByDeviceTypeAttributeId(deviceTypeAttributeId);

            //删除了设备属性也删除相关联的属性
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());

                if(attributeBigType.intValue()==1){
            List<DeviceAttribute> allByDeviceTypeAttributeId = deviceAttributeRepository.findAllByDeviceTypeAttributeId(deviceTypeAttributeId);
            if(allByDeviceTypeAttributeId.size()>0){
                for (int i = 0; i <allByDeviceTypeAttributeId.size() ; i++) {
                    deviceAttributeRepository.deleteByDeviceTypeAttributeId(deviceTypeAttributeId);
                }
            }

                }else if(attributeBigType.intValue()==2){
                    List<DeviceChannelAttribute> allByDeviceTypeAttributeId = deviceChannelAttributeRepository.findAllByDeviceTypeAttributeId(deviceTypeAttributeId);

                    if(allByDeviceTypeAttributeId.size()>0){
                        for (int i = 0; i <allByDeviceTypeAttributeId.size() ; i++) {

                            deviceChannelAttributeRepository.deleteByDeviceTypeAttributeId(deviceTypeAttributeId);
                        }
                    }



                }

            result.setResult("删除成功");
            return result;
        }



        result.setResult("删除失败");
        return result;
    }

    //添加设备属性或通道属性
    public DeviceTypeAttributeResult addDeviceTypeAttribute(Integer deviceTypeId, Integer attributeBigType, DeviceTypeAttribute deviceTypeAttribute) {
        Integer device_type_attribute_id = primaryKeyService.getPrimaryKey("DEVICE_TYPE_ATTRIBUTE_ID");
        deviceTypeAttribute.setDeviceTypeAttributeId(device_type_attribute_id);
        deviceTypeAttribute.setDeviceTypeId(deviceTypeId);
        deviceTypeAttribute.setAttributeBigType(attributeBigType);

        deviceTypeAttributeRepository.save(deviceTypeAttribute);


        //做关联TODO
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        List<Device> allByDeviceTypeId = deviceRepository.findAllByDeviceTypeId(deviceTypeId);
        if(allByDeviceTypeId.size()>0){

            if(attributeBigType.intValue()==1){

                for (int i = 0; i <allByDeviceTypeId.size() ; i++) {
                    DeviceAttribute deviceAttribute = new DeviceAttribute();
                    Integer device_attribute_id = primaryKeyService.getPrimaryKey("DEVICE_ATTRIBUTE_ID");
                    deviceAttribute.setDeviceAttributeId(device_attribute_id);
                    deviceAttribute.setDeviceId(allByDeviceTypeId.get(i).getDeviceId());
                    deviceAttribute.setDeviceAttributeType(deviceTypeAttribute.getAttributeType());
                    deviceAttribute.setDeviceAttributeNameEn(deviceTypeAttribute.getAttributeNameEn());
                    deviceAttribute.setDeviceAttributeNameCn(deviceTypeAttribute.getAttributeNameCn());
                    deviceAttribute.setDeviceAttributeValue("0");
                    deviceAttribute.setDeviceAttributeUnit(deviceTypeAttribute.getAttributeUnit());
                    deviceAttribute.setDeviceTypeAttributeId(deviceTypeAttribute.getDeviceTypeAttributeId());
                    deviceAttribute.setCreateTime(timestamp);
                    deviceAttributeRepository.save(deviceAttribute);
                }
            }else if(attributeBigType.intValue()==2){

                for (int i = 0; i <allByDeviceTypeId.size() ; i++) {
                    List<DeviceChannel> allByDeviceId = deviceChannelRepository.findAllByDeviceId(allByDeviceTypeId.get(i).getDeviceId());
                    if(allByDeviceId.size()>0){
                        for (int j = 0; j <allByDeviceId.size() ; j++) {
                            DeviceChannel deviceChannel = allByDeviceId.get(j);
                            Integer deviceChannelId = deviceChannel.getDeviceChannelId();


                            DeviceChannelAttribute deviceChannelAttribute = new DeviceChannelAttribute();
                            Integer device_attribute_id = primaryKeyService.getPrimaryKey("DEVICE_CHANNEL_ATTRIBUTE_ID");
                            deviceChannelAttribute.setChannelAttributeId(device_attribute_id);
                            deviceChannelAttribute.setDeviceChannelId(deviceChannelId);
                            deviceChannelAttribute.setChannelAttributeType(deviceTypeAttribute.getAttributeType());
                            deviceChannelAttribute.setChannelAttributeNameEn(deviceTypeAttribute.getAttributeNameEn());
                            deviceChannelAttribute.setChannelAttributeNameCn(deviceTypeAttribute.getAttributeNameCn());
                            deviceChannelAttribute.setChannelAttributeValue("0");
                            deviceChannelAttribute.setChannelAttributeUnit(deviceTypeAttribute.getAttributeUnit());
                            deviceChannelAttribute.setDeviceTypeAttributeId(deviceTypeAttribute.getDeviceTypeAttributeId());
                            deviceChannelAttribute.setCreateTime(timestamp);
                            deviceChannelAttributeRepository.save(deviceChannelAttribute);

                        }
                    }
                    }
                }

        }

        DeviceTypeAttributeResult result = new DeviceTypeAttributeResult(CommonCode.SUCCESS, deviceTypeAttribute);
        return result;
    }

    //通过ID修改设备属性或通道属性
    public DeviceTypeAttributeResult editDeviceTypeAttribute(Integer deviceTypeAttributeId, Integer attributeBigType, DeviceTypeAttribute deviceTypeAttribute) {

        DeviceTypeAttribute befordeviceTypeAttribute = deviceTypeAttributeRepository.findByDeviceTypeAttributeId(deviceTypeAttributeId);
        if (befordeviceTypeAttribute != null) {
            deviceTypeAttribute.setDeviceTypeAttributeId(befordeviceTypeAttribute.getDeviceTypeAttributeId());
            deviceTypeAttribute.setDeviceTypeId(befordeviceTypeAttribute.getDeviceTypeId());
            deviceTypeAttribute.setAttributeBigType(attributeBigType);
        }
        DeviceTypeAttribute save = deviceTypeAttributeRepository.save(deviceTypeAttribute);

        //修改了设备属性也修改相关联的属性
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        List<Device> allByDeviceTypeId = deviceRepository.findAllByDeviceTypeId(befordeviceTypeAttribute.getDeviceTypeId());
        if(allByDeviceTypeId.size()>0){

            if(attributeBigType.intValue()==1){
        List<DeviceAttribute> allByDeviceTypeAttributeId = deviceAttributeRepository.findAllByDeviceTypeAttributeId(deviceTypeAttributeId);
        if(allByDeviceTypeAttributeId.size()>0){
            for (int i = 0; i <allByDeviceTypeAttributeId.size() ; i++) {
                DeviceAttribute deviceAttribute = allByDeviceTypeAttributeId.get(i);
                deviceAttribute.setDeviceAttributeType(deviceTypeAttribute.getAttributeType());
                deviceAttribute.setDeviceAttributeNameEn(deviceTypeAttribute.getAttributeNameEn());
                deviceAttribute.setDeviceAttributeNameCn(deviceTypeAttribute.getAttributeNameCn());
                deviceAttribute.setDeviceAttributeValue("0");
                deviceAttribute.setDeviceAttributeUnit(deviceTypeAttribute.getAttributeUnit());
                deviceAttributeRepository.save(deviceAttribute);
            }
        }
            }else if(attributeBigType.intValue()==2){

                List<DeviceChannelAttribute> allByDeviceTypeAttributeId = deviceChannelAttributeRepository.findAllByDeviceTypeAttributeId(deviceTypeAttributeId);

                if(allByDeviceTypeAttributeId.size()>0){
                    for (int i = 0; i <allByDeviceTypeAttributeId.size() ; i++) {
                        DeviceChannelAttribute deviceChannelAttribute = allByDeviceTypeAttributeId.get(i);
                        deviceChannelAttribute.setChannelAttributeType(deviceTypeAttribute.getAttributeType());

                        deviceChannelAttribute.setChannelAttributeNameEn(deviceTypeAttribute.getAttributeNameEn());
                        deviceChannelAttribute.setChannelAttributeNameCn(deviceTypeAttribute.getAttributeNameCn());
                        deviceChannelAttribute.setChannelAttributeValue("0");
                        deviceChannelAttribute.setChannelAttributeUnit(deviceTypeAttribute.getAttributeUnit());
                        deviceChannelAttributeRepository.save(deviceChannelAttribute);
                    }
                }

            }
        }
        if (save != null) {
            DeviceTypeAttributeResult deviceTypeAttributeResult = new DeviceTypeAttributeResult(CommonCode.SUCCESS, deviceTypeAttribute);
            return deviceTypeAttributeResult;
        }
        return new DeviceTypeAttributeResult(CommonCode.FAIL, null);
    }


    //根据设备类型ID查询设备子属性
    public List findDeviceTypeAttributeSubList(Integer deviceTypeId) {
        String sql = "SELECT dt.device_type_desc,ec.const_desc AS atconst_desc,dtas.device_type_attribute_sub_id,dtas.device_type_id,\n" +
                "dtas.attribute_type,dtas.attribute_name_en,dtas.attribute_name_cn,dtas.attribute_unit,dtas.attribute_value_range FROM\n" +
                " device_type_attribute_sub_t dtas,device_type_t dt,(SELECT const_value,const_desc FROM sys_const_t WHERE const_group_name='ATTRIBUTE_TYPE')ec\n" +
                "  WHERE dt.device_type_id=dtas.device_type_id AND  ec.const_value=dtas.attribute_type AND dtas.device_type_id="+deviceTypeId;
        Query query = entityManager.createNativeQuery(sql);
        List<DeviceTypeAttributeSubVo> deviceTypeAttributeSubVoList = query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        return deviceTypeAttributeSubVoList;
    }

    //添加设备子属性
    public DeviceTypeAttributeSubResult addDeviceTypeAttributeSub(Integer deviceTypeId, DeviceTypeAttributeSub deviceTypeAttributeSub) {
        Integer device_type_attribute_sub_id = primaryKeyService.getPrimaryKey("DEVICE_TYPE_ATTRIBUTE_SUB_ID");
        deviceTypeAttributeSub.setDeviceTypeAttributeSubId(device_type_attribute_sub_id);
        deviceTypeAttributeSub.setDeviceTypeId(deviceTypeId);
        deviceTypeAttributeSub.setAttributeBigType(1);

        deviceTypeAttributeSubRepository.save(deviceTypeAttributeSub);

        //做关联TODO
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        List<Device> allByDeviceTypeId = deviceRepository.findAllByDeviceTypeId(deviceTypeId);
        if(allByDeviceTypeId.size()>0){

                for (int i = 0; i <allByDeviceTypeId.size() ; i++) {
                    DeviceAttributeSub deviceAttributeSub = new DeviceAttributeSub();
                    Integer device_attribute_sub_id = primaryKeyService.getPrimaryKey("DEVICE_ATTRIBUTE_SUB_ID");
                    deviceAttributeSub.setDeviceAttributeSubId(device_attribute_sub_id);
                    deviceAttributeSub.setDeviceId(allByDeviceTypeId.get(i).getDeviceId());
                    deviceAttributeSub.setDeviceAttributeType(deviceTypeAttributeSub.getAttributeType());
                    deviceAttributeSub.setDeviceAttributeNameCn(deviceTypeAttributeSub.getAttributeNameCn());
                    deviceAttributeSub.setDeviceAttributeNameEn(deviceTypeAttributeSub.getAttributeNameEn());
                    deviceAttributeSub.setDeviceAttributeValue("0");
                    deviceAttributeSub.setDeviceAttributeUnit(deviceTypeAttributeSub.getAttributeUnit());
                    deviceAttributeSub.setCreateTime(timestamp);
                    deviceAttributeSub.setDeviceTypeAttributeSubId(device_type_attribute_sub_id);
                    deviceAttributeSubRepository.save(deviceAttributeSub);
                }
            }



        DeviceTypeAttributeSubResult result = new DeviceTypeAttributeSubResult(CommonCode.SUCCESS, deviceTypeAttributeSub);
        return result;
    }



    //通过ID删除设备子属性
    public Result deleteDeviceTypeAttributeSubById(Integer deviceTypeAttributeSubId) {
        Result result = new Result();

        DeviceTypeAttributeSub deviceTypeAttributeSub= deviceTypeAttributeSubRepository.findByDeviceTypeAttributeSubId(deviceTypeAttributeSubId);

        if(deviceTypeAttributeSub!=null){
            deviceTypeAttributeSubRepository.deleteByDeviceTypeAttributeSubId(deviceTypeAttributeSubId);

            //同步删除
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            List<DeviceAttributeSub> byDeviceTypeAttributeSubId = deviceAttributeSubRepository.findByDeviceTypeAttributeSubId(deviceTypeAttributeSubId);

            if(byDeviceTypeAttributeSubId.size()>0){
                for (int i = 0; i <byDeviceTypeAttributeSubId.size() ; i++) {
                    deviceAttributeSubRepository.deleteByDeviceTypeAttributeSubId(deviceTypeAttributeSubId);
                }
            }



            result.setResult("删除成功");
            return result;


        }
        result.setResult("删除失败");
        return result;
    }

    //通过ID修改设备子属性
    public DeviceTypeAttributeSubResult editDeviceTypeAttributeSub(Integer deviceTypeAttributeSubId, DeviceTypeAttributeSub deviceTypeAttributeSub) {

        DeviceTypeAttributeSub befordeviceTypeAttributeSub = deviceTypeAttributeSubRepository.findByDeviceTypeAttributeSubId(deviceTypeAttributeSubId);
        if (befordeviceTypeAttributeSub != null) {
            deviceTypeAttributeSub.setDeviceTypeAttributeSubId(befordeviceTypeAttributeSub.getDeviceTypeAttributeSubId());
            deviceTypeAttributeSub.setDeviceTypeId(befordeviceTypeAttributeSub.getDeviceTypeId());
            deviceTypeAttributeSub.setAttributeBigType(1);
        }

        //修改了设备属性也修改相关联的属性
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        List<Device> allByDeviceTypeId = deviceRepository.findAllByDeviceTypeId(befordeviceTypeAttributeSub.getDeviceTypeId());
        if(allByDeviceTypeId.size()>0){

            List<DeviceAttributeSub> byDeviceAttributeSubId = deviceAttributeSubRepository.findByDeviceTypeAttributeSubId(deviceTypeAttributeSubId);

                if(byDeviceAttributeSubId.size()>0){
                    for (int i = 0; i <byDeviceAttributeSubId.size() ; i++) {
                        DeviceAttributeSub deviceAttributeSub = byDeviceAttributeSubId.get(i);
                        deviceAttributeSub.setDeviceAttributeType(deviceTypeAttributeSub.getAttributeType());
                        deviceAttributeSub.setDeviceAttributeNameEn(deviceTypeAttributeSub.getAttributeNameEn());
                        deviceAttributeSub.setDeviceAttributeNameCn(deviceTypeAttributeSub.getAttributeNameCn());
                        deviceAttributeSub.setDeviceAttributeValue("0");
                        deviceAttributeSub.setDeviceAttributeUnit(deviceTypeAttributeSub.getAttributeUnit());
                        deviceAttributeSubRepository.save(deviceAttributeSub);
                    }
                }

        }


        DeviceTypeAttributeSub save = deviceTypeAttributeSubRepository.save(deviceTypeAttributeSub);
        if (save != null) {
            DeviceTypeAttributeSubResult deviceTypeAttributeSubResult = new DeviceTypeAttributeSubResult(CommonCode.SUCCESS, deviceTypeAttributeSub);
            return deviceTypeAttributeSubResult;
        }
        return new DeviceTypeAttributeSubResult(CommonCode.FAIL, null);
    }


    //属性类型
    public List<SysConst> attributeTypeSub() {
        String sql = "SELECT const_value,const_desc FROM sys_const_t WHERE const_group_name='ATTRIBUTE_TYPE'";
        Query query = entityManager.createNativeQuery(sql);
        List<SysConst> sysConstList = query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        return sysConstList;
    }

    //日志类型
    public List<SysConst> logType() {
        String sql = "SELECT const_value,const_desc FROM sys_const_t WHERE const_group_name='DEVICE_LOG_TYPE'";
        Query query = entityManager.createNativeQuery(sql);
        List<SysConst> sysConstList = query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        return sysConstList;
    }

    //通过设备类型查询设备
    public List<Device> DeviceByTypeId(Integer deviceTypeId) {
        String sql = "SELECT * FROM device_t WHERE device_type_id="+deviceTypeId;
        Query query = entityManager.createNativeQuery(sql);
        List<Device> sysConstList = query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        return sysConstList;
    }

    @Autowired
    private PageService pageService;


    //删除设备
    public Result editChannelEnable(Integer deviceChannelId,Integer channelEnable) {
        Result result = new Result();
        DeviceChannel byDeviceChannelId = deviceChannelRepository.findByDeviceChannelId(deviceChannelId);
        if(byDeviceChannelId!=null){

            byDeviceChannelId.setChannelEnable(channelEnable);
            DeviceChannel save = deviceChannelRepository.save(byDeviceChannelId);
            if (save != null) {
                result.setResult("修改成功");
                result.setCode(200);
                return result;
            }
        }
        result.setResult("修改失败");
        result.setCode(404);
        return result;
    }

}
